package likou;

import java.util.Deque;
import java.util.LinkedList;

public class _394 {
    public static void main(String[] args) {
        System.out.println(decodeString("sd2[f2[e]g]i"));
    }

    public static String decodeString(String s) {
        Deque<String> deque = new LinkedList<>();
        int index = 0;
        while (index < s.length()) {
            if (s.charAt(index) == '[') {
                deque.offerLast("[");
                index++;
            } else if (s.charAt(index) == ']') {
                String now = deque.pollLast();//当前字符串
                StringBuilder sb = new StringBuilder();
                while (!deque.peekLast().equals("[")) {
                    now = deque.pollLast() + now;
                }
                if (deque.size() > 1 && deque.peekLast().equals("[")) {
                    deque.pollLast();
                    int preI = Integer.parseInt(deque.pollLast());
                    while (preI > 0) {
                        sb.append(now);
                        preI--;
                    }
                    while (deque.size() > 0 && !deque.peekLast().equals("[")) {
                        sb.insert(0, deque.pollLast());
                    }
                    deque.offerLast(sb.toString());
                }
                index++;
            } else {
                while (index < s.length() && s.charAt(index) != '[' && s.charAt(index) != ']') {
                    boolean p = s.charAt(index) >= '0' && s.charAt(index) <= '9';
                    StringBuilder sb = new StringBuilder();
                    if (p) {
                        while (p && s.charAt(index) != '[' && s.charAt(index) != ']') {
                            sb.append(s.charAt(index));
                            index++;
                            if (index == s.length()) break;
                            p = s.charAt(index) >= '0' && s.charAt(index) <= '9';
                        }
                    } else {
                        while (!p && s.charAt(index) != '[' && s.charAt(index) != ']') {
                            sb.append(s.charAt(index));
                            index++;
                            if (index == s.length()) break;
                            p = s.charAt(index) >= '0' && s.charAt(index) <= '9';
                        }
                    }
                    deque.offerLast(sb.toString());
                }
            }
        }
        StringBuilder sb = new StringBuilder("");
        while (deque.size() > 0) {
            sb.append(deque.pollFirst());
        }
        return sb.toString();
    }
}
